﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


namespace NetFrame.JobService
{
    using System.Reflection;

    using Microsoft.Scripting;
    using IronPython.Hosting;
    using Persistance;
    using Model;
    using LogService;
    using SqliteORM;

    /// <summary>
    /// 为Job提供服务的
    /// </summary>
    public class JobService 
    {
        public delegate void InfoLog(object o);
        /// <summary>
        /// 加载所有Job,重新全部执行
        /// </summary>
        public static void LoadJobs(string jobname="")
        {
            try
            {
                var persistance = new BasePersistance<Job>();
                var jobs = persistance.Adapter.Select().Where(t=>t.RowStatus==1);
                //创建时间过滤

                foreach (Job job in jobs)
                {
                    if (!string.IsNullOrEmpty(jobname))
                    {
                        if (jobname != job.JobName) continue;
                    }
                    var arr = job.Triger.Split('.');
                    if (!job.JobName.StartsWith("python", true, null))
                    {
                        SchedulerManager.Instance.AddCronTriggerJob(
                            job.Triger,
                            job.JobName,
                            job.RegCron,
                            (ExecteDelegate)
                            Delegate.CreateDelegate(
                                typeof (ExecteDelegate),
                                Type.GetType("TC.Finance.JobService.Core." + arr[0]).GetMethod(arr[1])));
                    }
                    else
                    {
                        var ed = CreatePythonDeledate(job.Id);
                        if (ed != null)
                        {
                            SchedulerManager.Instance.AddCronTriggerJob(
                                job.Triger,
                                job.JobName,
                                job.RegCron,
                                ed);
                        }
                    }
                }

                SchedulerManager.Instance.Start();


                jobs = persistance.Adapter.Select().Where(t => t.RowStatus == 0);
                foreach (Job item in jobs)
                {
                    SchedulerManager.Instance.UnscheduleJob(item.Triger);
                }
            }catch(Exception ex)
            {
                Log.Error(ex);
            }

        }

        static ExecteDelegate  CreatePythonDeledate(Int64 jobid)
        {
            
            ExecteDelegate b = () =>
                {
                    try
                    {
                        Log.Info("Python Script开始执行" + jobid.ToString());
                        var persistance = new BasePersistance<Job>();
                        var jobscript = persistance.Adapter.Select().Where(Where.Equal("Id", jobid)).SingleOrDefault().Script;
                        if (string.IsNullOrWhiteSpace(jobscript)) return ;
                        var engine = Python.CreateEngine();
                        engine.Runtime.LoadAssembly(Assembly.GetAssembly(typeof(JobService)));
                        var code = engine.CreateScriptSourceFromString(
                            jobscript, SourceCodeKind.Statements);
                        var scope = engine.Runtime.CreateScope();
                        //scope.SetVariable("DataBase", persistance.WriteDatabase);
                        scope.SetVariable("Log",new InfoLog((object info)=> Log.Info(info.ToString())) );
                        code.Execute(scope);
                        Log.Info("Python Script执行完毕");
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex);
                    }
                };
            return b;
        }
        

        /// <summary>
        /// 暂停计划任务
        /// </summary>
        public static void StopJob(string jobname)
        {
            if (string.IsNullOrEmpty(jobname)) return;
            var scheduler = SchedulerManager.Instance.Scheduler;
            scheduler.PauseJob(jobname, SchedulerManager.DefaultJobGroup);
        }

    

        /// <summary>
        /// 重启计划任务
        /// </summary>
        public static void ResumeJob(string jobname)
        {
            if (string.IsNullOrEmpty(jobname)) return;
            var scheduler = SchedulerManager.Instance.Scheduler;
            scheduler.ResumeJob(jobname, SchedulerManager.DefaultJobGroup);
        }
    }
}